import 'dart:io';
import 'dart:convert';
import 'dart:math' as math;
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:image_picker/image_picker.dart';
import 'package:path/path.dart' as path;
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:flutter_markdown/flutter_markdown.dart';
import '../models/note.dart';
import '../repositories/note_repository.dart';
import '../widgets/image_preview_widget.dart';
import '../widgets/markdown_preview_widget.dart';

class AddEditNoteScreen extends StatefulWidget {
  final int? noteId;
  
  const AddEditNoteScreen({super.key, this.noteId});

  @override
  State<AddEditNoteScreen> createState() => _AddEditNoteScreenState();
}

// 定义视图模式枚举
enum ViewMode { edit, preview }

class _AddEditNoteScreenState extends State<AddEditNoteScreen> {
  final _formKey = GlobalKey<FormState>();
  final _titleController = TextEditingController();
  final _contentController = TextEditingController(); // 保留用于兼容性
  final _noteRepository = NoteRepository();
  final _imagePicker = ImagePicker();
  
  // Markdown编辑器控制器
  final _markdownController = TextEditingController();
  String _markdownContent = '';
  
  bool _isLoading = false;
  bool _isEditMode = false;
  String _selectedCategory = '时政'; // 默认分类
  File? _imageFile;
  String? _imageUrl;
  ViewMode _viewMode = ViewMode.edit; // 默认使用编辑模式
  bool _userSelectedViewMode = false; // 跟踪用户是否手动切换了视图模式
  
  // 预定义的分类列表
  final List<String> _categories = [
    '时政', 
    '常识判断', 
    '言语理解与表达', 
    '数量关系', 
    '判断推理', 
    '资料分析'
  ];
  
  @override
  void initState() {
    super.initState();
    _isEditMode = widget.noteId != null;
    
    // 初始化Markdown内容
    _markdownContent = '';
    
    // 根据屏幕宽度设置默认视图模式
    WidgetsBinding.instance.addPostFrameCallback((_) {
      final screenWidth = MediaQuery.of(context).size.width;
      setState(() {
        // 如果屏幕宽度小于600，默认使用编辑模式，否则使用预览模式
        _viewMode = screenWidth < 600 ? ViewMode.edit : ViewMode.preview;
      });
    });
    
    if (_isEditMode) {
      _loadNoteData();
    }
  }
  
  Future<void> _loadNoteData() async {
    setState(() => _isLoading = true);
    
    try {
      final note = await _noteRepository.getNoteById(widget.noteId!);
      
      if (note != null) {
        // 加载Markdown内容
        if (note.richContent != null && note.richContent!.isNotEmpty) {
          try {
            // 尝试解析保存的富文本内容为Markdown
            _markdownContent = note.richContent!;
            _markdownController.text = note.richContent!;
          } catch (e) {
            print('解析富文本内容失败: $e');
            // 如果解析失败，使用普通文本内容初始化
            _markdownContent = note.content;
            _markdownController.text = note.content;
          }
        } else {
          // 如果没有富文本内容，使用普通文本内容初始化
          _markdownContent = note.content;
          _markdownController.text = note.content;
        }
        
        setState(() {
          _titleController.text = note.title;
          _contentController.text = note.content; // 保留普通文本，以便兼容
          _selectedCategory = note.category.isNotEmpty ? note.category : '时政';
          _imageUrl = note.imageUrl;
          _isLoading = false;
        });
      } else {
        _showErrorSnackBar('找不到笔记数据');
        setState(() => _isLoading = false);
      }
    } catch (e) {
      setState(() => _isLoading = false);
      _showErrorSnackBar('加载笔记数据失败: $e');
    }
  }
  
  // 获取存储路径的方法
  Future<String> _getStoragePath() async {
    // 检查是否为桌面平台
    if (Platform.isWindows || Platform.isLinux || Platform.isMacOS) {
      // 桌面平台使用固定路径
      return 'D:\\000\\my-web\\学习宝库\\图片\\笔记';
    }
    
    // 移动平台处理
    if (Platform.isAndroid) {
      final DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
      final AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo;
      
      // 请求存储权限
      final status = await Permission.storage.request();
      if (!status.isGranted) {
        throw Exception('需要存储权限才能保存图片');
      }
      
      // 获取存储目录
      Directory? directory;
      try {
        // 尝试获取外部存储目录
        directory = await getExternalStorageDirectory();
        if (directory == null) {
          throw Exception('无法获取外部存储目录');
        }
        
        // 构建路径：Download/考试宝/图片/笔记
        String basePath = directory.path;
        // 如果路径包含Android/data，则需要回退到外部存储根目录
        if (basePath.contains('Android/data')) {
          List<String> paths = basePath.split('/');
          int index = paths.indexOf('Android');
          if (index > 0) {
            // 回退到外部存储根目录
            basePath = paths.sublist(0, index).join('/');
          }
        }
        
        return path.join(basePath, 'Download', '学习宝库', '图片', '笔记');
      } catch (e) {
        print('获取存储路径失败: $e');
        // 如果无法获取外部存储，则使用应用内部存储
        directory = await getApplicationDocumentsDirectory();
        return path.join(directory.path, 'Download', '学习宝库', '图片', '笔记');
      }
    } else if (Platform.isIOS) {
      // iOS平台使用应用文档目录
      final directory = await getApplicationDocumentsDirectory();
      return path.join(directory.path, 'Download', '学习宝库', '图片', '笔记');
    } else {
      // 其他平台使用临时目录
      final directory = await getTemporaryDirectory();
      return path.join(directory.path, 'Download', '学习宝库', '图片', '笔记');
    }
  }
  
  Future<void> _pickImage() async {
    try {
      // 检查是否在Web平台
      if (kIsWeb) {
        // Web平台不支持本地文件选择
        _showErrorSnackBar('Web平台不支持本地图片上传');
        return;
      }
      
      final pickedFile = await _imagePicker.pickImage(source: ImageSource.gallery);
      
      if (pickedFile != null) {
        // 获取存储路径
        final String baseDir = await _getStoragePath();
        
        // 确保目录存在
        final directory = Directory(baseDir);
        if (!await directory.exists()) {
          await directory.create(recursive: true);
        }
        
        final fileName = path.basename(pickedFile.path);
        final String savedPath = Platform.isWindows 
            ? '$baseDir\\$fileName' 
            : path.join(baseDir, fileName);
        final savedImage = await File(pickedFile.path).copy(savedPath);
        
        print('笔记图片已保存到: ${savedImage.path}'); // 添加日志以便调试
        
        setState(() {
          _imageFile = savedImage;
          _imageUrl = savedImage.path; // 保存图片路径
        });
      }
    } catch (e) {
      print('选择图片失败: $e');
      _showErrorSnackBar('选择图片失败: $e');
    }
  }
  
  Future<void> _saveNote() async {
    if (!_formKey.currentState!.validate()) return;
    
    setState(() => _isLoading = true);
    
    try {
      // 处理图片路径
      String? finalImageUrl = _imageUrl;
      if (_imageFile != null) {
        // 在实际应用中，这里应该上传图片到服务器或保存到本地存储
        // 这里简单地使用文件路径作为URL
        finalImageUrl = _imageFile!.path;
      }
      
      // 获取Markdown内容
      final plainText = _markdownContent.trim();
      final richContentJson = _markdownContent; // 直接保存Markdown文本
      
      final now = DateTime.now().millisecondsSinceEpoch;
      
      final note = Note(
        id: _isEditMode ? widget.noteId : null,
        title: _titleController.text.trim(),
        content: plainText, // 保存纯文本内容，以便兼容
        richContent: richContentJson, // 保存Markdown内容
        category: _selectedCategory,
        imageUrl: finalImageUrl,
        created_at: _isEditMode ? 0 : now, // 创建时间只在新建时设置
        updated_at: now, // 更新时间总是当前时间
      );
      
      if (_isEditMode) {
        await _noteRepository.updateNote(note);
      } else {
        await _noteRepository.addNote(note);
      }
      
      setState(() => _isLoading = false);
      _showSuccessSnackBar(_isEditMode ? '笔记已更新' : '笔记已创建');
      
      // 返回上一页
      if (mounted) Navigator.pop(context, true); // 返回true表示数据已更改
    } catch (e) {
      setState(() => _isLoading = false);
      _showErrorSnackBar(_isEditMode ? '更新笔记失败: $e' : '创建笔记失败: $e');
    }
  }
  
  void _showSuccessSnackBar(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text(message, style: const TextStyle(fontFamily: 'FangSong', fontFamilyFallback: ['仿宋', 'FangSong', 'FangSong_GB2312'])))
    );
  }
  
  void _showErrorSnackBar(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message, style: const TextStyle(fontFamily: 'FangSong', fontFamilyFallback: ['仿宋', 'FangSong', 'FangSong_GB2312'])),
        backgroundColor: Colors.red,
      ),
    );
  }
  
  @override
  void dispose() {
    _titleController.dispose();
    _contentController.dispose();
    _markdownController.dispose();
    super.dispose();
  }
  

  

  

  


  // 插入Markdown语法
  void _insertMarkdownSyntax(String prefix, String suffix) {
    // 获取当前光标位置
    final TextEditingValue value = _markdownController.value;
    final int start = value.selection.baseOffset;
    final int end = value.selection.extentOffset;
    final String text = value.text;
    final int textLength = text.length;
    
    // 确保光标位置有效
    if (start < 0 || end < 0 || start > textLength || end > textLength) {
      // 在文本末尾添加
      final newText = text + prefix + suffix;
      _markdownController.value = TextEditingValue(
        text: newText,
        selection: TextSelection.collapsed(
          offset: newText.length - suffix.length,
        ),
      );
    } else if (start == end) {
      // 在光标位置插入
      final safeStart = start.clamp(0, textLength);
      final newText = text.substring(0, safeStart) + prefix + suffix + text.substring(safeStart);
      _markdownController.value = TextEditingValue(
        text: newText,
        selection: TextSelection.collapsed(
          offset: safeStart + prefix.length,
        ),
      );
    } else {
      // 将选中的文本包裹在语法中
      final safeStart = start.clamp(0, textLength);
      final safeEnd = end.clamp(0, textLength);
      final actualStart = safeStart < safeEnd ? safeStart : safeEnd;
      final actualEnd = safeStart < safeEnd ? safeEnd : safeStart;
      
      final selectedText = text.substring(actualStart, actualEnd);
      final newText = text.substring(0, actualStart) + prefix + selectedText + suffix + text.substring(actualEnd);
      _markdownController.value = TextEditingValue(
        text: newText,
        selection: TextSelection.collapsed(
          offset: actualStart + prefix.length + selectedText.length + suffix.length,
        ),
      );
    }
    
    // 更新_markdownContent以保持同步
    setState(() {
      _markdownContent = _markdownController.text;
    });
  }
  
  // 构建预览组件，支持表格和分数格式
  Widget _buildPreviewWidget() {
    // 创建基础文本样式
    final baseStyle = const TextStyle(
      fontFamily: 'FangSong', 
      fontFamilyFallback: ['仿宋', 'FangSong', 'FangSong_GB2312'],
      fontSize: 16,
    );
    
    // 获取当前容器宽度
    final screenWidth = MediaQuery.of(context).size.width;
    final previewWidth = screenWidth - 40;
    
    // 使用MarkdownPreviewWidget组件，支持表格和分数格式
    return Container(
      width: previewWidth, // 设置固定宽度，防止内容溢出
      child: MarkdownPreviewWidget(
        content: _markdownContent,
        style: baseStyle,
        maxLines: null, // 完整显示所有内容
      ),
    );
  }
  
  // 根据屏幕宽度自动调整视图模式
  void _adjustViewModeByScreenWidth() {
    final screenWidth = MediaQuery.of(context).size.width;
    ViewMode newMode;
    
    // 根据屏幕宽度设置合适的视图模式
    if (screenWidth < 600) {
      // 小屏幕设备默认使用编辑模式，但保留用户已选择的模式
      if (!_userSelectedViewMode) {
        newMode = ViewMode.edit;
      } else {
        // 保持当前模式不变
        newMode = _viewMode;
      }
    } else {
      // 大屏幕设备默认使用预览模式，但不强制改变用户选择
      if (!_userSelectedViewMode) {
        newMode = ViewMode.preview;
      } else {
        // 保持用户选择的模式
        newMode = _viewMode;
      }
    }
    
    // 只有当模式需要改变时才更新状态，避免不必要的重建
    if (_viewMode != newMode) {
      setState(() {
        _viewMode = newMode;
      });
    }
  }

  


  @override
  Widget build(BuildContext context) {
    // 在每次构建时检查屏幕尺寸并调整视图模式
    _adjustViewModeByScreenWidth();
    
    return Scaffold(
      appBar: AppBar(
        title: Text(_isEditMode ? '编辑笔记' : '添加笔记', style: const TextStyle(fontFamily: 'FangSong', fontFamilyFallback: ['仿宋', 'FangSong', 'FangSong_GB2312'])),
        centerTitle: true,
      ),
      body: _isLoading && _isEditMode
          ? const Center(child: CircularProgressIndicator())
          : Form(
              key: _formKey,
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: SingleChildScrollView(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.stretch,
                    children: [
                      // 标题输入
                      TextFormField(
                        controller: _titleController,
                        decoration: const InputDecoration(
                          labelText: '标题',
                          border: OutlineInputBorder(),
                          labelStyle: TextStyle(fontFamily: 'FangSong', fontFamilyFallback: ['仿宋', 'FangSong', 'FangSong_GB2312']),
                        ),
                        style: const TextStyle(fontFamily: 'FangSong', fontFamilyFallback: ['仿宋', 'FangSong', 'FangSong_GB2312']),
                        validator: (value) {
                          if (value == null || value.trim().isEmpty) {
                            return '请输入笔记标题';
                          }
                          return null;
                        },
                      ),
                      const SizedBox(height: 16),
                      
                      // 分类选择器
                      DropdownButtonFormField<String>(
                        value: _selectedCategory,
                        decoration: const InputDecoration(
                          labelText: '分类',
                          border: OutlineInputBorder(),
                          labelStyle: TextStyle(fontFamily: 'FangSong', fontFamilyFallback: ['仿宋', 'FangSong', 'FangSong_GB2312']),
                        ),
                        items: _categories.map((String category) {
                          return DropdownMenuItem<String>(
                            value: category,
                            child: Text(
                              category, 
                              style: TextStyle(
                                fontFamily: 'FangSong', 
                                fontFamilyFallback: const ['仿宋', 'FangSong', 'FangSong_GB2312'],
                                color: Theme.of(context).textTheme.bodyLarge?.color ?? Colors.black,
                              ),
                            ),
                          );
                        }).toList(),
                        onChanged: (String? newValue) {
                          if (newValue != null) {
                            setState(() {
                              _selectedCategory = newValue;
                            });
                          }
                        },
                        style: TextStyle(
                          fontFamily: 'FangSong', 
                          fontFamilyFallback: const ['仿宋', 'FangSong', 'FangSong_GB2312'],
                          color: Theme.of(context).textTheme.bodyLarge?.color ?? Colors.black,
                        ),
                      ),
                      const SizedBox(height: 16),
                      
                      // 内容标签
                      const Text(
                        '内容',
                        style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold, fontFamily: 'FangSong', fontFamilyFallback: ['仿宋', 'FangSong', 'FangSong_GB2312']),
                      ),
                      const SizedBox(height: 8),
                      
                      // Markdown编辑器
                      Container(
                        height: 600,
                        decoration: BoxDecoration(
                          border: Border.all(color: Colors.grey),
                          borderRadius: BorderRadius.circular(4),
                        ),
                        child: Column(
                          children: [
                            // Markdown工具栏
                            Container(
                              padding: const EdgeInsets.symmetric(horizontal: 8),
                              child: Column(
                                children: [
                                  // 第一行工具栏
                                  Row(
                                    children: [
                                      IconButton(
                                        icon: const Icon(Icons.format_bold),
                                        onPressed: () {
                                          _insertMarkdownSyntax('**', '**');
                                        },
                                        tooltip: '粗体',
                                      ),
                                      IconButton(
                                        icon: const Icon(Icons.format_italic),
                                        onPressed: () {
                                          _insertMarkdownSyntax('*', '*');
                                        },
                                        tooltip: '斜体',
                                      ),
                                      IconButton(
                                        icon: const Icon(Icons.strikethrough_s),
                                        onPressed: () {
                                          _insertMarkdownSyntax('~~', '~~');
                                        },
                                        tooltip: '删除线',
                                      ),
                                      IconButton(
                                        icon: const Icon(Icons.format_underlined),
                                        onPressed: () {
                                          _insertMarkdownSyntax('`', '`');
                                        },
                                        tooltip: '行内代码',
                                      ),
                                      IconButton(
                                        icon: const Icon(Icons.format_quote),
                                        onPressed: () {
                                          _insertMarkdownSyntax('\n> ', '');
                                        },
                                        tooltip: '引用',
                                      ),
                                      IconButton(
                                        icon: const Icon(Icons.horizontal_rule),
                                        onPressed: () {
                                          _insertMarkdownSyntax('\n---\n', '');
                                        },
                                        tooltip: '分隔线',
                                      ),
                                      IconButton(
                                        icon: const Icon(Icons.table_chart),
                                        onPressed: () {
                                          _insertMarkdownSyntax('\n| 列1 | 列2 | 列3 |\n|-----|-----|-----|\n| 内容1 | 内容2 | 内容3 |\n', '');
                                        },
                                        tooltip: '表格',
                                      ),
                                    ],
                                  ),
                                  // 第二行工具栏 - 标题级别
                                  Row(
                                    children: [
                                      IconButton(
                                        icon: const Text('H1', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 12)),
                                        onPressed: () {
                                          _insertMarkdownSyntax('\n# ', '');
                                        },
                                        tooltip: '一级标题',
                                      ),
                                      IconButton(
                                        icon: const Text('H2', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 12)),
                                        onPressed: () {
                                          _insertMarkdownSyntax('\n## ', '');
                                        },
                                        tooltip: '二级标题',
                                      ),
                                      IconButton(
                                        icon: const Text('H3', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 12)),
                                        onPressed: () {
                                          _insertMarkdownSyntax('\n### ', '');
                                        },
                                        tooltip: '三级标题',
                                      ),
                                      IconButton(
                                        icon: const Text('H4', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 12)),
                                        onPressed: () {
                                          _insertMarkdownSyntax('\n#### ', '');
                                        },
                                        tooltip: '四级标题',
                                      ),
                                      IconButton(
                                        icon: const Icon(Icons.format_list_bulleted),
                                        onPressed: () {
                                          _insertMarkdownSyntax('\n- ', '');
                                        },
                                        tooltip: '无序列表',
                                      ),
                                      IconButton(
                                        icon: const Icon(Icons.format_list_numbered),
                                        onPressed: () {
                                          _insertMarkdownSyntax('\n1. ', '');
                                        },
                                        tooltip: '有序列表',
                                      ),
                                      IconButton(
                                        icon: const Icon(Icons.link),
                                        onPressed: () {
                                          _insertMarkdownSyntax('[链接文本](', ')');
                                        },
                                        tooltip: '链接',
                                      ),
                                      IconButton(
                                        icon: const Icon(Icons.code),
                                        onPressed: () {
                                          _insertMarkdownSyntax('\n```\n', '\n```');
                                        },
                                        tooltip: '代码块',
                                      ),

                                    ],
                                  ),
                                ],
                              ),
                            ),
                            // 编辑和预览区域 - 优化布局，添加切换功能
                            Expanded(
                              child: Column(
                                children: [
                                  // 添加切换按钮
                                  Row(
                                    children: [
                                      Expanded(
                                        child: Row(
                                          mainAxisAlignment: MainAxisAlignment.center,
                                          children: [
                                            TextButton(
                                              onPressed: () {
                                                setState(() {
                                                  _viewMode = ViewMode.edit;
                                                  _userSelectedViewMode = true;
                                                });
                                              },
                                              style: ButtonStyle(
                                                backgroundColor: MaterialStateProperty.all<Color>(
                                                  _viewMode == ViewMode.edit ? Colors.grey.shade200 : Colors.transparent
                                                ),
                                              ),
                                              child: const Text('编辑', style: TextStyle(fontFamily: 'FangSong', fontFamilyFallback: ['仿宋', 'FangSong', 'FangSong_GB2312'])),
                                            ),
                                            TextButton(
                                              onPressed: () {
                                                setState(() {
                                                  _viewMode = ViewMode.preview;
                                                  _userSelectedViewMode = true;
                                                });
                                              },
                                              style: ButtonStyle(
                                                backgroundColor: MaterialStateProperty.all<Color>(
                                                  _viewMode == ViewMode.preview ? Colors.grey.shade200 : Colors.transparent
                                                ),
                                              ),
                                              child: const Text('预览', style: TextStyle(fontFamily: 'FangSong', fontFamilyFallback: ['仿宋', 'FangSong', 'FangSong_GB2312'])),
                                            ),
                                          ],
                                        ),
                                      ),
                                    ],
                                  ),
                                  // 内容区域 - 根据视图模式显示不同布局
                                  Expanded(
                                    child: _viewMode == ViewMode.edit
                                      ? Container(
                                          padding: const EdgeInsets.all(8),
                                          child: Scrollbar(
                                            thumbVisibility: true,
                                            controller: ScrollController(),
                                            child: TextField(
                                              controller: _markdownController,
                                              minLines: 10, // 最小显示10行
                                              maxLines: null, // 允许无限扩展行数
                                              decoration: const InputDecoration(
                                                hintText: '请输入Markdown内容...',
                                                border: InputBorder.none,
                                                contentPadding: EdgeInsets.all(16.0),
                                              ),
                                              style: const TextStyle(
                                                fontFamily: 'FangSong', 
                                                fontFamilyFallback: ['仿宋', 'FangSong', 'FangSong_GB2312'],
                                                fontSize: 16
                                              ),
                                              keyboardType: TextInputType.multiline,
                                              onChanged: (value) {
                                                setState(() {
                                                  _markdownContent = value;
                                                });
                                              },
                                              scrollPhysics: const ClampingScrollPhysics(),
                                            ),
                                          ),
                                        )
                                      : Container(
                                          padding: const EdgeInsets.all(8),
                                          child: Scrollbar(
                                            thumbVisibility: true,
                                            controller: ScrollController(),
                                            child: SingleChildScrollView(
                                              physics: const ClampingScrollPhysics(),
                                              child: _buildPreviewWidget(),
                                            ),
                                          ),
                                        ),
                                  ),
                                ],
                              ),
                            ),
                          ],
                        ),
                      ),
                      
                      // 隐藏的验证器
                      Visibility(
                        visible: false,
                        child: TextFormField(
                          controller: TextEditingController(text: ''),
                          validator: (value) {
                            if (_markdownContent.trim().isEmpty) {
                              return '请输入笔记内容';
                            }
                            return null;
                          },
                        ),
                      ),
                      
                      const SizedBox(height: 16),
                      
                      // 图片选择区域
                      Card(
                        child: Padding(
                          padding: const EdgeInsets.all(16.0),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Row(
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                children: [
                                  const Text(
                                    '图片',
                                    style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold, fontFamily: 'FangSong', fontFamilyFallback: ['仿宋', 'FangSong', 'FangSong_GB2312']),
                                  ),
                                  Row(
                                    children: [
                                      IconButton(
                                        icon: const Icon(Icons.add_photo_alternate, color: Colors.blue),
                                        onPressed: _pickImage,
                                        tooltip: '添加图片',
                                      ),
                                      if (_imageFile != null || _imageUrl != null)
                                        IconButton(
                                          icon: const Icon(Icons.delete, color: Colors.red),
                                          onPressed: () {
                                            setState(() {
                                              _imageFile = null;
                                              _imageUrl = null;
                                            });
                                          },
                                          tooltip: '删除图片',
                                        ),
                                    ],
                                  ),
                                ],
                              ),
                              if (_imageFile != null || _imageUrl != null) ...[
                                const SizedBox(height: 8),
                                ClipRRect(
                                  borderRadius: BorderRadius.circular(8),
                                  child: _buildImagePreview(),
                                ),
                              ],
                            ],
                          ),
                        ),
                      ),
                      
                      const SizedBox(height: 24),
                      
                      // 保存按钮
                      ElevatedButton.icon(
                        onPressed: _isLoading ? null : _saveNote,
                        icon: _isLoading
                            ? const SizedBox(
                                width: 20,
                                height: 20,
                                child: CircularProgressIndicator(strokeWidth: 2),
                              )
                            : const Icon(Icons.save),
                        label: Text(_isEditMode ? '更新笔记' : '保存笔记', style: const TextStyle(fontFamily: 'FangSong', fontFamilyFallback: ['仿宋', 'FangSong', 'FangSong_GB2312'])),
                      ),
                    ],
                  ),
                ),
              ),
            ),
    );
  }
  
  Widget _buildImagePreview() {
    String? imagePath;
    
    if (_imageFile != null) {
      // 显示本地文件
      imagePath = _imageFile!.path;
    } else if (_imageUrl != null && _imageUrl!.isNotEmpty) {
      // 显示网络图片或本地路径图片
      imagePath = _imageUrl;
    } else {
      // 没有图片时不显示任何内容
      return const SizedBox.shrink();
    }
    
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        ImagePreviewWidget(
          imageUrl: imagePath!,
          height: 200,
          width: double.infinity,
          fit: BoxFit.contain,
          showPath: true,
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.end,
          children: [
            TextButton(
              onPressed: () {
                setState(() {
                  _imageFile = null;
                  _imageUrl = null;
                });
              },
              child: const Text('删除图片'),
            ),
          ],
        ),
      ],
    );
  }
}